package com.cskaoyan.servlet;


import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.common.CommonServlet;
import com.cskaoyan.util.JacksonUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin/auth/*")
public class AdminAuthServlet extends CommonServlet {
    public static final String USER_KEY = "market_user_id";


    // login
    public BaseRespVo login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        String jsonStr = request.getReader().readLine();

        Map<String,String> map = JacksonUtil.read(jsonStr, Map.class);
        String username = map.get("username");
        String password = map.get("password");
//        response.setHeader("Access-Control-Allow-Origin", "jc.com");
        Cookie cookie = new Cookie("location", "wuhan");
        cookie.setDomain("jc.com");
        response.addCookie(cookie);

        Integer adminId = 1;
        if (adminId != 0) { // 登录成功
            Map<String,Object> data = new HashMap<>();
            data.put("token", "admin-token");
            HashMap<String, Object> adminInfo = new HashMap<>();
            adminInfo.put("avatar", "");
            adminInfo.put("nickName", "");
            data.put("adminInfo", adminInfo);

            return BaseRespVo.ok(data); // CommonServlet中的method.invoke方法的返回值
        } else {
            return BaseRespVo.msg("用户名或密码错误");
        }

    }

    // logout
    public BaseRespVo logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        return BaseRespVo.msg("已注销");
    }
    // info
    public BaseRespVo info(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Integer adminId = (Integer) session.getAttribute(USER_KEY);

        Map<String,Object> data = new HashMap<>();
        data.put("avatar", "");
        data.put("nickName", "");
        data.put("perms", Arrays.asList("*"));
        data.put("roles", Arrays.asList("*"));
        return BaseRespVo.ok(data);
    }
    // modify
    public BaseRespVo modify(HttpServletRequest request, HttpServletResponse response) {
        // 写修改业务代码
        return BaseRespVo.msg("修改成功");
    }
    // remove
    public BaseRespVo remove(HttpServletRequest request, HttpServletResponse response) {
        // 写删除业务代码
        return BaseRespVo.msg("删除成功");
    }
    public BaseRespVo list(HttpServletRequest request, HttpServletResponse response) {
        // 写删除业务代码
        return BaseRespVo.msg("aaa");
    }

}
